import { useState, useEffect } from "react";
import { Form, Modal, Popconfirm, message, Popover, Button, Input, Row, Col, Space, Tooltip } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import Style from "./index.module.less";
import { InputNumber } from "@/views/components/PrefixPlaceholder";
import StashSelect from "@/views/components/StashSelect";
import {
	updatePurchaseorder,
	querySellNumBySysGoodsId,
	getProductByCode,
	inventoryTotalInventoryList,
	productOutboundOrderCreateProductOutboundOrder
} from "../service";
import { QuestionCircleOutlined } from "@ant-design/icons";
import CommonZjfImg from "@/views/components/CommonZjfImg";
import styles from "./index.module.less";
import { isEmpty, find, findIndex, cloneDeep, forEach } from "lodash";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import { formatAmount } from "@/utils/utils.jsx";
import GoodsListModal from "@/pages/GoodsModule/combinationGoods/component/GoodsListModal";
const AddOutboundOrderModal = ({ visible, handleCancel, fetchList, record, actionType, warehouseList }) => {
	const [form] = Form.useForm();
	const [addVisible, setAddVisible] = useState(0);
	const [dataSource, setDataSource] = useState([]);
	const [selectName, setSelectName] = useState("");
	const [selectedWarehouse, setSelectedWarehouse] = useState(null);
	const [selectedWarehouseName, setSelectedWarehouseName] = useState(null);
	const [storeList, setStoreList] = useState([]);
	useEffect(() => {
		setDataSource(record.combinationSubList);
	}, [visible]);
	// 表头数据
	const columns = [
		{
			title: "序号",
			dataIndex: "index",
			key: "index",
			width: 80,
			render: (t, r, i) => i + 1
		},
		{
			title: "系统商品名称",
			dataIndex: "goodsName",
			key: "goodsName",
			width: 300,
			render: (text, record) => {
				return (
					<div className={styles.goodsBox}>
						<div className={styles.goodsImg}>
							<img src={record.image} />
						</div>
						<div>
							<Popover
								content={
									<div>
										<div>{record.skuName}</div>
										<div>{record.specs}</div>
									</div>
								}
							>
								<div className="textOverflowMultiTwo">{record.skuName}</div>
								<div className="textOverflowMultiOne">{record.specs}</div>
							</Popover>
							<div>
								<span>商品编码：</span>
								<span>{record.skuCode}</span>
							</div>
							<div>
								<span>价格：</span>
								<span className="common-color9">¥{record.purchasePrice || 0}</span>
							</div>
						</div>
					</div>
				);
			}
		},
		{
			title: "供应商",
			dataIndex: "supplierName",
			key: "supplierName",
			width: 100,
			render: (text, record, index) => <div>{record.supplierRow.supplierName}</div>
		},
		{
			title: "供应商商品名称",
			dataIndex: "supplierSkuName",
			key: "supplierSkuName",
			render: (text, record, index) => {
				return (
					<div>
						<div className={styles.titleRender}>
							<div style={{ width: "100%" }}>{goodsNameRender(record, index)}</div>
						</div>
						<div>
							<div>
								{(record?.batchList || []).map((item, index1) => (
									<div key={index1}>
										<div className={styles.batchList} style={{ marginRight: 5 }}>
											<div style={{ width: "10%" }}>批次{index1 + 1}</div>
											<div>
												<InputNumber
													value={item.batchUnitPrice}
													placeholder="请输入退货单价"
													onChange={e => handlePriceChange(e, record, index, index1)}
													max={9999}
													origin
													min={0}
													style={{ width: "80%" }}
													precision={2}
												/>
											</div>
											<div>
												<InputNumber
													placeholder="请输入退货数"
													value={item.batchNum ? item.batchNum : record.total}
													style={{ width: "80%" }}
													onChange={e => handleNumChange(e, record, index, index1)}
												/>
											</div>
										</div>
									</div>
								))}
							</div>
						</div>
					</div>
				);
			}
		},
		{
			title: "正品可售数",
			dataIndex: "saleableNum",
			key: "saleableNum",
			width: 100,
			render: (text, record, index) => {
				console.log(record, "rescsa");
				return <div style={{ marginTop: 10 }}>{record.saleableNum}</div>;
			}
		},
		{
			title: "价格统计",
			dataIndex: "price",
			key: "price",
			width: 100,
			render: (text, record, index) => {
				return (
					<div>
						<div className={styles.titleRender}></div>
						<div className="common-color9" style={{ marginTop: 10 }}>
							¥{totalMoneyRender(record)}
						</div>
						<div className={styles.goodsBox}>
							<div className={styles.goodsImg}></div>
							<div></div>
						</div>
						<div>
							<div>
								{(record?.batchList || []).map((item, index1) => (
									<div key={index1}>
										<div className={styles.batchList1}>
											<div className="common-color9">¥{item.batchNum * item.batchUnitPrice}</div>
										</div>
									</div>
								))}
							</div>
						</div>
					</div>
				);
			}
		},
		{
			title: "操作",
			width: 150,
			dataIndex: "action",
			key: "action",
			render: (text, record, index) => {
				return (
					<div>
						<div className={styles.titleRender}>
							<div>{operateRender(record, index)}</div>
						</div>
						<div className={styles.goodsBox}>
							<div className={styles.goodsImg}></div>
							<div></div>
						</div>
						<div>
							<div>
								{(record?.batchList || []).map((item, index1) => (
									<div key={index1}>
										<div className={styles.batchList}>
											<Button
												onClick={() => {
													delBatchList(record, index, index1);
												}}
												type="link"
												size="small"
												style={{ fontSize: "12px", marginTop: 24 }}
												disabled={record.batchList.length == 1}
											>
												删除
											</Button>
										</div>
									</div>
								))}
							</div>
						</div>
					</div>
				);
			}
		}
	];

	const CheckGoodsModalProps = {
		addVisible,
		selectName,
		storeList,
		// isExactMatch: 1,
        matchOrNot: 1,
		memberPricedisabled: true,
		selectTitle: (
			<>
				选择商品
                {/* （申请会员价仅支持精准匹配的商品）
				<Tooltip title="同供应商商品匹配的多个系统商品，提交申请会一同提交且会员价一致">
					<QuestionCircleOutlined />
				</Tooltip> */}
			</>
		),
		handleOk() {},
		handleCancel() {
			setAddVisible(0);
		}
	};
	const handleWarehouseChange = async value => {
		setSelectedWarehouse(value.value);
		setSelectedWarehouseName(value.label);
		console.log(value, "value");
		if (dataSource?.length > 0) {
			const arr = cloneDeep(dataSource);

			const skuIdList = arr?.map(item => item.id);

			const { data, success } = await inventoryTotalInventoryList({ skuIdList: skuIdList });
			if (success) {
				data.forEach(i => {
					console.log(value.value, "selectedWarehouse");
					const id = value.value ? value.value : warehouseList?.current[0]?.options[0]?.id;
					arr?.forEach(g => {
						if (g.id == i.skuId) {
							console.log(g, "ggggggggggg");
							console.log(id, "ssssssssssss");
							console.log(i, "iiiiiiiiiii");
							console.log(i.esInventory[id].saleableNum, "i.esInventory[id].saleableNum");
							g.saleableNum = i.esInventory[id].saleableNum;
						}
					});
				});
				console.log(arr, "dataSource");
				setDataSource(arr);
				setAddVisible(false);
			}
			// getInventoryTotalInventoryList(dataSource);
		}
	};

	// 回车搜索商品
	const commonPressEnter = async value => {
		if (value) {
			const { data, success } = await getProductByCode({ code: value, warehouseId: selectedWarehouse, isExactMatch: 1 });
			if (success) {
				data.forEach(i => {
					const goodsSkuMatches = i.goodsSkuMatches || [];
					const defaultSupplierRow = goodsSkuMatches.filter(x => x.isDefault === 1)[0];
					i.supplierRow = (defaultSupplierRow !== undefined ? defaultSupplierRow : goodsSkuMatches[0]) || {};
				});
				handleDealData(data);
			}
		} else {
			message.warning("请输入系统商品编码/商品唯一码");
		}
		form.setFieldValue("inputValue", "");
	};
	//供应商商品名称的渲染
	const goodsNameRender = (record, index) => {
		return (
			<div className={styles.goodsBox}>
				<div className={styles.goodsImg}>
					<CommonZjfImg img={record.supplierSkuImage} storeId={record.supplierId} />
				</div>
				<div>
					<div className="textOverflowMultiTwo">{record.supplierRow.supplierSkuName}</div>
					<div className="textOverflowMultiOne">{record.supplierRow.supplierSkuSpecs}</div>
					<div>
						<span>商品编码：</span>
						<span>{record.supplierRow.supplierSkuId}</span>
					</div>
					<div>
						<span>价格：</span>
						<span className="common-color9">¥{record.purchasePrice || 0}</span>
					</div>
				</div>
			</div>
		);
	};
	//价格统计渲染
	const totalMoneyRender = record => {
		let total = 0;
		if (record && record.batchList.length) {
			record.batchList.forEach(item => {
				total = total + (item.batchNum ? item.batchNum : record.total) * item.batchUnitPrice;
			});
		}
		return formatAmount(total);
	};

	//操作的渲染
	const operateRender = (record, index) => {
		return (
			<span className="opera-span-common">
				<span
					onClick={() => {
						addBatchList(record, index);
					}}
					className="mr10"
				>
					新建批次
				</span>
				<Popconfirm title="确定删除?" onConfirm={() => deleteRecord(index, record)} okText="确定" cancelText="取消">
					<span>删除</span>
				</Popconfirm>
			</span>
		);
	};

	//采购价格的修改
	const handlePriceChange = (val, record, index, index1) => {
		const arr = cloneDeep(dataSource);
		arr[index]["batchList"][index1]["batchUnitPrice"] = val;
		setDataSource(arr);
	};

	//批次退货数量的修改
	const handleNumChange = (val, record, index, index1) => {
		const arr = cloneDeep(dataSource);
		const reg = /^[1-9]\d*$/;
		// const val = e.target.value;
		const obj = arr[index]["batchList"][index1];
		if (reg.test(val)) {
			arr[index]["batchList"][index1]["batchNum"] = val;
		} else {
			message.info("请输入正整数");
		}
		setDataSource(arr);
	};

	//新建批次
	const addBatchList = (record, index) => {
		const arr = cloneDeep(dataSource);
		if (arr[index]["batchList"].length < 5) {
			arr[index]["batchList"].push({
				batchNum: 1,
				batchUnitPrice: record.purchasePrice || 0,
				flag: record.purchaseRefundId ? 2 : undefined //已存在商品新增批次需要打标记
			});
			setDataSource(arr);
		} else {
			message.info("最多添加5个批次");
		}
	};

	//删除批次
	const delBatchList = (record, index, index1) => {
		const arr = cloneDeep(dataSource);
		arr[index]["batchList"].splice(index1, 1);
		setDataSource(arr);
	};

	//删除单个商品
	const deleteRecord = (index, record) => {
		const arr = cloneDeep(dataSource);
		arr.splice(index, 1);
		setDataSource(arr);
	};

	const getInventoryTotalInventoryList = async val => {
		const arr = cloneDeep(val);
		console.log(val, "val");
		const skuIdList = arr?.map(item => item.id);

		const { data, success } = await inventoryTotalInventoryList({ skuIdList: skuIdList });
		if (success) {
			data.forEach(i => {
				console.log(selectedWarehouse, "selectedWarehouse");
				const id = selectedWarehouse ? selectedWarehouse : warehouseList?.current[0]?.options[0]?.id;
				arr?.forEach(g => {
					if (g.id == i.skuId) {
						console.log(g, "ggggggggggg");
						console.log(id, "ssssssssssss");
						console.log(i, "iiiiiiiiiii");
						g.saleableNum = i.esInventory[id].saleableNum;
					}
				});
			});
			console.log(arr, "val");
			setDataSource(arr);
			setDataSource(arr);
			setAddVisible(false);
		}
	};

	inventoryTotalInventoryList;
	//处理选择商品数据
	const handleDealData = async selectedRows => {
		console.log(selectedRows, "selectedRows");
		const list = [];
		selectedRows.forEach(item => {
			item.total = item?.num ? item?.num : 1;
			list.push(item.id);
		});
		const params = {
			warehouseId: form.getFieldValue("warehouseId"),
			sysGoodsIds: list.join(",")
		};
		const { success, data = [] } = await querySellNumBySysGoodsId(params);
		if (true) {
			const arr = cloneDeep(selectedRows);
			selectedRows.forEach((item, index1) => {
				const obj = find(data, ["id", item.id]);
				let index = findIndex(arr, ["id", item.id]);
				if (index > -1) {
					arr.splice(index, 1, {
						...item,
						salableNum: obj?.salableNum || 0,
						batchNo: +new Date() + item.id
					});
				} else {
					arr.push({
						...item,
						salableNum: obj?.salableNum || 0,
						batchNo: +new Date() + item.id
					});
				}
			});
			//重新组装数据,将选中的提到外层
			arr.map(t => {
				t.batchList = [
					{
						batchNum: "",
						batchUnitPrice: t.purchasePrice || 0
					}
				];
			});
			if (dataSource && dataSource.length > 0) {
				const filterLsit = Object.values(
					[...dataSource, ...arr].reduce((accumulator, currentValue) => {
						if (accumulator[currentValue.id]) {
							accumulator[currentValue.id].total += currentValue.total;
						} else {
							accumulator[currentValue.id] = { ...currentValue };
						}
						return accumulator;
					}, {})
				);
				filterLsit.forEach(i => {
					i.batchList.map(x => (x.batchNum = i.total));
					totalMoneyRender(i);
				});

				getInventoryTotalInventoryList(filterLsit);
			} else {
				arr.forEach(i => {
					i.batchList.map(x => (x.batchNum = i.total));
					totalMoneyRender(i);
				});
				getInventoryTotalInventoryList(arr);
			}
		}
	};
	const onOk = () => {
		form
			.validateFields()
			.then(val => {
				handleSubmit(val);
			})
			.catch(info => {});
	};
	//提交采购退货单
	const handleSubmit = val => {
		if (dataSource == undefined || dataSource.length == 0) {
			return message.error("请选择系统商品");
		} else {
			handleAddpurchaseReturn(val);
		}
	};

	//新建采购退货单
	const handleAddpurchaseReturn = async val => {
		const arr = cloneDeep(dataSource);
		const list = [];
		arr.forEach(x => {
			if (x.batchList) {
				x.batchList.forEach((y, index) => {
					console.log(y, "ssssss");
					list.push({
						batchNameSome: "批次" + index,
						batchName: "批次" + x.batchNo + index,
						// batchName: "批次" + (index + 1),
						batchNum: y.batchNum,
						batchTotalPrice: Number(y.batchNum) * Number(y.batchUnitPrice),
						batchUnitPrice: y.batchUnitPrice,
						salableNum: x.salableNum,
						totalPrice: x.batchList.reduce((acc, item) => acc + item.batchNum * item.batchUnitPrice, 0),
						supplierSkuId: x.supplierRow.supplierSkuId,
						supplierSkuImage: x.supplierRow.supplierSkuImage,
						supplierSkuName: x.supplierRow.supplierSkuName,
						supplierSkuPrice: x.purchasePrice || 0,
						supplierSkuSpec: x.supplierRow.supplierSkuSpecs,
						supplierSpuCode: x.supplierRow.supplierSpuCode,
						supplierName: x.supplierRow.supplierName,
						supplierId: x.supplierRow.supplierId,
						skuCode: x.skuCode,
						skuId: x.id,
						returnTotalNum: y.batchNum,
						skuImage: x.image,
						skuName: x.skuName,
						price: x.purchasePrice || 0,
						skuSpec: x.colorSpecifications,
						spuCode: x.spuCode,
						deliveryWarehouseId: selectedWarehouse ? selectedWarehouse : warehouseList?.current[0]?.options[0]?.id,
						deliveryWarehouseName: selectedWarehouseName ? selectedWarehouseName : warehouseList?.current[0]?.options[0]?.label
					});
				});
			}
		});

		const batchNameMap = {};

		list.forEach(item => {
			const key = `${item.batchNameSome}-${item.supplierId}`;
			if (!batchNameMap[key]) {
				batchNameMap[key] = item.batchName;
			}
		});
		list.forEach(item => {
			const key = `${item.batchNameSome}-${item.supplierId}`;
			item.batchName = batchNameMap[key];
		});

		const priceIndex = findIndex(list, o => {
			//价格是否都填写
			return o.batchUnitPrice == "";
		});

		if (priceIndex > -1) {
			return Modal.info({
				title: "",
				width: 520,
				centered: true,
				okText: "知道了",
				content: (
					<div>
						<p>退货单价有误，请检查并修改</p>
					</div>
				),
				onOk() {}
			});
		}
		const { success } = await productOutboundOrderCreateProductOutboundOrder(list);
		if (success) {
			message.success(`您已经成功创建${list ? list.length : 0}张采购单，总计${arr.length}个商品`);
			handleCancel();
			fetchList();
		}
	};

	const handleChildValue = value => {
		value.forEach(i => {
			if (i.goodsSkuMatches1) {
				const goodsSkuMatches = i.goodsSkuMatches.filter(x => x.id === i.goodsSkuMatches1);
				i.supplierRow = goodsSkuMatches[0];
			} else {
				const goodsSkuMatches = i.goodsSkuMatches || [];
				const defaultSupplierRow = goodsSkuMatches.filter(x => x.isDefault === 1)[0];
				i.supplierRow = (defaultSupplierRow !== undefined ? defaultSupplierRow : goodsSkuMatches[0]) || {};
			}
		});
		handleDealData(value);
	};

	const AddHandleClick = name => {
		// setSelectName(name);
		setAddVisible(1);
	};
	const onCancel = () => {
		handleCancel();
		form.resetFields();
	};

	return (
		<CommonModal
			title={{ title: "新建退货出库单" }}
			visible={true}
			onOk={onOk}
			onCancel={onCancel}
			width="1296px"
			minHeight="150px"
			footer={
				<Row style={{ justifyContent: "end" }}>
					<Col>
						<Space>
							<Button size="middle" onClick={onCancel}>
								取消
							</Button>
							{actionType == "add" && (
								<Button size="middle" type="primary" onClick={onOk}>
									创建出库单
								</Button>
							)}
							{actionType !== "add" && (
								<Button size="middle" type="primary" onClick={onOk}>
									确定
								</Button>
							)}
						</Space>
					</Col>
				</Row>
			}
		>
			<div className={Style.detail_inner}>
				<SubTitle symbol as="s2" title="设置出仓仓库" wrapStyle={{ marginBottom: 16 }} />
				<Form form={form} name="mark-unuaual-modal" style={{ marginTop: "12px" }}>
					<Row>
						<Col span={6}>
							<Form.Item label="" name="deliveryWarehouseId">
								<StashSelect
									value={selectedWarehouse}
									origin={origin}
									defaultValue={warehouseList?.current[0].options[0]}
									warehouseList={warehouseList.current}
									placeholder={"选择出库仓库"}
									onChange={handleWarehouseChange}
								/>
							</Form.Item>
						</Col>
					</Row>
					<SubTitle symbol as="s2" title="商品设置" wrapStyle={{ marginBottom: 16 }} />
					<div className="flex" style={{ justifyContent: "space-between" }}>
						<Button className="mb10" onClick={() => AddHandleClick("add")}>
							新增商品
						</Button>
						<Form.Item name="inputValue" label="" style={{ width: 300 }}>
							<Input onPressEnter={e => commonPressEnter(e.target.value)} placeholder="系统商品编码 / 商品唯一码便捷创建"></Input>
						</Form.Item>
					</div>
					<CommonTable style={{ margin: "16px 0px" }} dataSource={dataSource} pagination={false} columns={columns} />
				</Form>
			</div>
			{addVisible == 1 && <GoodsListModal onGoodsSkuListSelected={handleChildValue} {...CheckGoodsModalProps} />}
		</CommonModal>
	);
};

export default AddOutboundOrderModal;
